<!-- 物料投入记录 -->
<template>
  <BaseMainSlot>
    <template v-slot:searchbox>
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="searchPage()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">投入鱼塘</div>
            <el-select v-model="fishPondId" filterable clearable @change="fishPondChange(), productionBatchId = ''">
              <el-option v-for="(item, index) in pondList" :key="index" :label="item.pondName" :value="item.fishPondId" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">批次编号</div>
            <el-select v-model="productionBatchId" filterable clearable>
              <el-option v-for="(item, index) in batchList" :key="index"
                :label="`${item.mnecode}_${item.varietyName}`" :value="item.productionBatchId" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">物料名称</div>
            <el-select v-model="materialId" filterable clearable>
              <el-option v-for="(item, index) in materialList" :key="index" :label="item.name" :value="item.materialId" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">物料投入人</div>
            <el-input v-model="staffName" clearable />
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">投入日期</div>
            <el-date-picker v-model="inputDate" type="datetimerange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:btnsBar>
      <ActionBar :add-active="addActive" :del-active="delActive" :page-no="162" @add="add" @del="del"
        :hasImportData="true" @getNewlistData="queryPageList" :importApi="'base/materialRecord/excelImport'"
        :upDownApi="'base/materialRecord/downloadTemplate'" />
    </template>
    <template v-slot:categoryBox>
      <div class="totalList" v-if="showMaterialTotal">
        <div>物料总数：{{ totalAmount }}</div>
        <!-- <div @click="showMaterialInfo">用料详情</div> -->
      </div>
    </template>
    <template v-slot:content>
      <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" class="margin-top10px" stripe
        border height="calc(100% - 50px)" :row-key="row => { return row.materialRecordId; }"
        @selection-change="handleSelectionChange" @select="select" @select-all="selectAll">
        <el-table-column type="selection" width="55" :reserve-selection="true"
          :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">
            {{ scoped.row.materialRecordId ? scoped.$index + 1 : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="materialName" label="物料名称" />
        <el-table-column prop="amount" label="投入物料量">
          <template v-if="scope.row.materialRecordId" slot-scope="scope">
            {{ scope.row.amount ? scope.row.amount : '0' }}{{ scope.row.basicUnitName }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="投入数量">
          <template v-if="scope.row.materialRecordId" slot-scope="scope">
            {{((scope.row.amount || 0) / (scope.row.ratio||0)).toFixed(2)}}
            {{ scope.row.auxiliaryUnitName || '' }}
            <!-- {{ scope.row.auxiliaryUnitName ? scope.row.auxiliaryUnitName :''}} -->
          </template>
        </el-table-column>
        <el-table-column label="物料规格">
          <template v-if="scope.row.materialRecordId" slot-scope="scope">
            {{ scope.row.ratio ? scope.row.ratio : '' }}
            {{ scope.row.basicUnitName ? scope.row.basicUnitName : '' }}
            {{ scope.row.auxiliaryUnitName ? '/' + scope.row.auxiliaryUnitName : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="batchName" label="投入批次"  width="160" />
        <el-table-column prop="pondName" label="投入鱼塘" />
        <el-table-column prop="staffName" label="物料投入人" width="160">
          <template v-if="scope.row.materialRecordId" slot-scope="scope">
            {{ scope.row.staffName&& scope.row.staffName!=='null' ? scope.row.staffName : '未选择物料投入人' }}
          </template>
        </el-table-column>
        <el-table-column label="投入证明">
          <template v-if="scope.row.materialRecordId" slot-scope="scope">
            <el-button v-if="scope.row.fileIdList" class="text-btn-cursor" type="text" size="small"
              @click="showPicture(scope.row.fileIdList)">点击查看</el-button>
            <span class="btnstyle" v-else>无投入证明</span>
          </template>
        </el-table-column>
        <el-table-column label="投入说明">
          <template v-if="scope.row.materialRecordId" slot-scope="scope">
            <span class="btnstyle" :style="{ color: scope.row.explain ? 'blue' : '' }"
              @click="open(scope.row.explain, '投入说明')">{{ scope.row.explain ? '查看说明' : '无说明'
              }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template v-if="scope.row.materialRecordId" slot-scope="scope">
            <span class="btnstyle" :style="{ color: scope.row.remark ? 'blue' : '' }"
              @click="open(scope.row.remark, '备注')">{{
                scope.row.remark ? '查看备注' : '无备注' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inputDate" label="投塘日期" />
        <el-table-column v-if="audit === true && success === ''" prop="deadDate" label="审核结果">
          <template v-if="scoped.row.deadRecordId" slot-scope="scoped">
            <div class="table-btns-box">
              <div v-if="scoped.row.audit === true && scoped.row.success === true" class="table-btns edit-btns">
                <p>通过审核</p>
              </div>
              <div v-if="scoped.row.audit === true && scoped.row.success === false" class="table-btns del-btns">
                <p>未通过审核</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="120" label="操作">
          <template v-if="scope.row.materialRecordId" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" @click="edit(scope.row)">修改
            </el-button>
            <el-button class="text-btn-cursor1 text-btn-cursor" type="text" size="small"
              @click="delOne(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :title="(titleText || '') + '投料凭证'" :visible="showPictureDialog" @close="closePictureDialog"
        width="800px">
        <div v-if="fileIdList.length > 0" class="pictureDialogStyle">
          <template v-for="url, index in imageDataList">
            <el-image :key="index" style="width: 200px; height: 200px;margin: 5px;" v-if="url.indexOf('image') !== -1"
              :src="url" :preview-src-list="[url]">
            </el-image>
          </template>
          <template v-for="url, index in imageDataList">
            <div style="width: 200px; height: 200px;margin: 5px; position: relative;" :key="index"
              v-if="url.indexOf('image') == -1">
              <iframe style="width: 200px; height: 200px; pointer-events: none;" :src="url" frameborder="0"></iframe>
              <div @click="pdfData = url" style="position: absolute; top: 0;left: 0;width: 200px; height: 200px;"></div>
            </div>
          </template>
        </div>
        <div v-else class="empty-content"><span>暂无凭证</span></div>
      </el-dialog>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
        @changeCurrentPage="changeCurrentPage" />
      <AddEditDialog ref="addEditDialog" :now-chance-stau="nowChanceStau" :title-text="titleText"
        :edit-object="editObject" :staff-list="staffList" :pond-list="pondList" :material-list="materialList"
        :show.sync="showAddEditDialog" @closeDialog="closeDialog" @cancelDialog="cancel" />
      <div v-if="pdfData"
        style="position: fixed;top:0;left: 0;width:100vw;height: 100vh;background: #33333352;z-index: 99998999;">
        <div @click="pdfData = null"
          style="color: #ffffff; font-size: 18px; text-align: right; position: absolute;right: 20px;top: 20px; cursor: pointer;">
          关 闭</div>
        <iframe style="width:700px; height: calc(100% - 20px); margin-left: calc(50% - 350px)" :src="pdfData"
          frameborder="0"></iframe>
      </div>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import CategoryBar from "@/components/CategoryBar";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import AddEditDialog from "./components/add-edit-dialog.vue";
import { mymixin } from "@/utils/mixin";
import { blobToBase64 } from "@/utils/convert";
import { mapGetters } from 'vuex';

import InputManageApi from "@/api/input-manage"
import BatchMangeApi from "@/api/batch-mange"
import DocumentApi from "@/api/document"
import MaterialApi from "@/api/basic-info-manage/material"
import FishPondApi from "@/api/basic-info-manage/fishPond"
import StaffApi from "@/api/basic-info-manage/staff";
export default {
  name: 'MaterialInputReport',
  components: { ActionBar, Pagination, BaseMainSlot, AddEditDialog, CategoryBar },
  mixins: [mymixin],
  data() {
    return {
      pdfData: '',
      audit: "",//是否审核
      success: "",//审核是否成功
      productionBatchId: "",//批次编号
      fishPondId: "",//养殖鱼塘ID
      materialId: '',//经手人
      staffName: '',//经手人
      inputDate: [],//经手日期
      checkedIdList: [],
      pondList: [],//全部鱼塘
      batchList: [],//全部未完成批次
      FishVarietyData: [],//全部品种
      staffList: [],//全部员工/经手人
      fileIdList: [],//文件ID
      materialList: [],//物料
      imageDataList: [],//物料
      //分类列表
      categoryList: [
        { id: 0, name: "待审核", value: 'REVIEW' },
        { id: 1, name: "审核通过", value: 'PASS' },
        { id: 2, name: "审核未通过", value: 'NOT_PASS' },
      ],
      showAddEditDialog: false,
      showPictureDialog: false,
      showDialog: false,
      auditType: undefined,
      totalAmount: 0,
      showMaterialTotal: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    this.queryPageList();
  },
  mounted() {
    this.queryFishPond()
    this.queryBatchMange()
    this.queryStaff()
    this.queryMaterial()
  },
  methods: {
    open(text = '标题', title = "内容") {
      this.$alert(text, title, {
        confirmButtonText: '确定'
      });
    },
    searchPage() {
      this.currentPage = 1
      this.queryPageList();
      this.statisticInputNum();
    },
    showPicture(fileIdList) {
      if (fileIdList !== null && fileIdList.length > 0) {
        this.fileIdList = fileIdList
        fileIdList.forEach(async item => {
          await DocumentApi.fileDownload({ fileId: item }).then(res => {
            blobToBase64(res.data).then(res2 => {

              this.imageDataList.push(res2)
            })
          })
        })
        this.showPictureDialog = true;
      } else (
        this.fileIdList = [],
        this.$message.info('未上传投入证明')
      )
    },
    closePictureDialog() {
      this.showPictureDialog = false
      this.resetActionBar()
      this.imageDataList = []
    },
    jumpWebPage(url) {
      window.open(url)
    },
    categoryBar(item) {
      this.auditType = item.value
      this.queryPageList()
    },
    // 鱼塘下拉
    fishPondChange() {
      this.queryBatchMange()
    },
    //查询可选批次 
    queryBatchMange() {
      BatchMangeApi.queryByCondition({ status: 'UN_COMPLETE', fishPondId: this.fishPondId }).then(res => {
        this.batchList = res.data;
      })
    },
    //查询可选物料
    queryMaterial() {
      MaterialApi.queryByCondition({}).then(res => {
        this.materialList = res.data;
      })
    },
    //查询可选鱼塘
    queryFishPond() {
      FishPondApi.queryByCondition().then(res => {
        this.pondList = res.data;
      })
    },
    //查询经手人
    queryStaff() {
      StaffApi.queryByCondition().then(res => {
        this.staffList = res.data;
      })
    },
    statisticInputNum() {
      let params = {
        productionBatchId: this.productionBatchId || '',
        materialId: this.materialId || '',
        fishPondId: this.fishPondId || '',
        staffName: this.staffName || '',
        inputEndDate: this.inputDate && this.inputDate.length > 0 ? this.inputDate[1] : '',
        inputStartDate: this.inputDate && this.inputDate.length > 0 ? this.inputDate[0] : ''
      };
      let notNullLenght = 0
      let totalAmount = 0
      for (let key in params) {
        if (params[key]) {
          notNullLenght++
        }
      }
      if (notNullLenght >= 2) {
        MaterialApi.statisticInputNum({
          ...params,
          "ignoreMaterialTypeNoList": ["FEED"],
          auditType: "REVIEW"
        }).then(res => {
          this.showMaterialTotal = true
          if (res.success) {
            res.data.forEach(item => {
              totalAmount += item.totalAmount
              console.log(totalAmount)
            });
            this.totalAmount = totalAmount
          }
        });
        console.log(totalAmount)
      } else {
        this.showMaterialTotal = false
      }
    },
    queryPageList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ignoreMaterialTypeNoList: ['FEED'],  //排除饲料
          auditType: "REVIEW"
        }
      };
      // if (this.auditType !== undefined) params.entity.auditType = this.auditType;
      if (this.productionBatchId) params.entity.productionBatchId = this.productionBatchId;
      if (this.materialId) params.entity.materialId = this.materialId;
      if (this.fishPondId) params.entity.fishPondId = this.fishPondId;
      if (this.staffName) params.entity.staffName = this.staffName;
      if (this.inputDate && this.inputDate.length > 0) {
        params.entity.inputEndDate = this.inputDate[1];
        params.entity.inputStartDate = this.inputDate[0]
      } else {
        params.entity.inputEndDate = '';
        params.entity.inputStartDate = ''
      };
      InputManageApi.queryPageByCondition(params).then(res => {
        if (res.success === true) {
          let data = res.data || {};
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.queryPageList();
    },
    selectAll(list) {
      let notvalue = true
      list.forEach(item => {
        if (!item.materialRecordId) {
          notvalue = false
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    select(list) {
      let notvalue = true
      list.forEach(item => {
        if (!item.materialRecordId) {
          notvalue = false
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    handleSelectionChange(list) {
      this.checkedIdList = [];
      let notvalue = true
      let emptyList = []
      this.checkedIdList = list.map(item => {
        if (item.materialRecordId) {
          return item.materialRecordId
        } else {
          notvalue = false
          emptyList.push(item)
          return ""
        }
      });
      if (notvalue === false) {
        // this.$message.warning("不可选择空数据！");
        this.toggleNoSelection(emptyList)
        return
      }
      if (this.checkedIdList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 表格删除
    delmessage() {
      InputManageApi.delListById({ idList: this.checkedIdList }).then(res => {
        if (res.success) {
          this.queryPageList();
          this.$message.success("删除成功");
          this.resetActionBar();
        }
      });
    },
    // king单个删除
    delOne(row) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          InputManageApi.delById({ id: row.materialRecordId }).then(res => {
            if (res.success === true) {
              this.$message.success("删除成功!");
              this.queryPageList();
              this.resetActionBar();
            }
          });
        })
        .catch(() => {
          this.resetActionBar();
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 添加
    add() {
      this.nowChanceStau = 'add'
      this.titleText = "添加"
      this.addActive = false;
      this.delActive = false;
      this.showAddEditDialog = true
    },
    async queryBatch(id) {
      let res = await BatchMangeApi.queryByCondition({ productionBatchId: id })
      if (res && res.success && res.data && res.data.length) {
        return res.data[0].status
      } else {
        return null
      }
    },
    // 修改
    async edit(row) {
      let batchStatus = ''
      batchStatus = await this.queryBatch(row.productionBatchId)
      if (batchStatus) {
        if (batchStatus == 'COMPLETED') {
          this.$message.info('该批次已完成不可编辑！')
          return
        }
      } else {
        this.$message.info('该批次不存在！')
        return
      }
      if (row.materialRecordId) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = 'edit'
        this.titleText = "修改"
        this.addActive = false;
        this.delActive = false;
        this.showAddEditDialog = true
        sessionStorage.setItem('kingfishPondId', JSON.stringify(row))
      } else {
        this.editObject = {}
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.empty-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 150px;
  font-size: 20px;
}

.text-btn-cursor1 {
  color: #e70808;
}

::v-deep .el-image {
  opacity: 0.8;
  transition: all 0.2s;
}

::v-deep .el-image:hover {
  border: 1px solid #cecece;
  opacity: 1;
}

.totalList {
  background: #ffffff;
  margin-bottom: 10px;
  border-radius: 6px;
  padding: 10px;
  display: flex;
  justify-content: flex-start;
  flex-wrap: nowrap;
}

.pictureDialogStyle {
  min-height: 200px;
  max-height: 425px;
  overflow: auto;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.btnstyle {
  font-size: 12px;
  color: #666666;
  cursor: pointer;
}
</style>